import axios from 'axios';

import AuthenticationManager from '../api/authentication/authentication-manager';
import { authenticationExpiredDialog } from '../components/shared/dialogs/authentications/authentication-expired';
import { createDialog } from '../components/shared/dialogs/dynamic-dialogs';
import { DialogTypes } from '../components/shared/dialogs/dynamic-dialogs/types-mapping';
import { ErrorStatus } from '../constants/error-status';
import Routes from '../constants/routes';
import Router from './router';

function initAxios() {
    const errorMessage = 'Something went wrong. Please try again later';

    axios.interceptors.response.use(
        function (response) {
            return response;
        },
        function (error) {
            if (typeof error.response === 'undefined') {
                // 'A network error occurred.'
                // 'This could be a CORS issue or a dropped internet connection.'
                return Promise.reject({
                    code: ErrorStatus.NETWORK_ERROR,
                    message: errorMessage
                });
            }
            const { response } = error;
            if (response.data?.error?.code === ErrorStatus.ORGANIZATION_NOT_FOUND) {
                setTimeout(() => Router.go(Routes.WRONG_WALLET));
            } else if (
                response.data?.error?.code === ErrorStatus.AUTHENTICATION_IS_INVALID &&
                response.config.url
            ) {
                const url = new URL(response.config.url).pathname;
                if (![AuthenticationManager.Endpoint.CHECK].includes(url)) {
                    createDialog(DialogTypes.AUTHENTICATION_EXPIRED, () =>
                        authenticationExpiredDialog()
                    );
                }
            }
            return Promise.reject(error);
        }
    );
}

export { initAxios };
